﻿using Newtonsoft.Json;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using Yz.Base;
using Yz.Core.Apis;

namespace Yz.ApiService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Filters.Add(new APIExceptionAttribute()); //注册全局异常过滤器
            // Web API 路由
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
           "DefaultApi",
           "{controller}/{action}",
            defaults: new { controller = "ApiBase", action = "Get" }
         );
            config.Routes.MapHttpRoute(
                "Api",
                "api/{controller}/{action}"
            );

            var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
            jsonFormatter.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            jsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
        }
    }
    /// <summary>
    ///     WebAPI异常捕获
    /// </summary>
    public class APIExceptionAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            filterContext.Exception.Data.Add("WebAPI系统", "未定义的全局异常处理");
            filterContext.Response = filterContext.Request.CreateResponse(
                ApiDataFactory.CreateApiData(new ApiModel(), ApiDataCode.error, ApiDataMsg.error));
        }
    }
}
